package com.zbo.servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zbo.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private final StudentService studentService = new StudentService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        // 读取 JSON 请求体
        String jsonBody = req.getReader().lines().reduce("", (a, b) -> a + b);
        JSONObject requestBody = JSON.parseObject(jsonBody);

        String username = requestBody.getString("username");
        String password = requestBody.getString("password");
        String captcha = requestBody.getString("captcha"); // 获取验证码

        // 验证码验证（使用注册专用 Session Key）
        if (!validateCaptcha(req, captcha, "KAPTCHA_REGISTER")) {
            sendJsonResponse(resp, false, "验证码错误");
            return;
        }

        // 输入验证
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            sendJsonResponse(resp, false, "用户名和密码不能为空");
            return;
        }

        // 调用 Service 注册
        boolean success = studentService.register(username.trim(), password);

        PrintWriter out = resp.getWriter();
        if (success) {
            sendJsonResponse(resp, true, "注册成功");
        } else {
            sendJsonResponse(resp, false, "用户名已存在");
        }
        out.flush();
    }

    // 发送 JSON 响应
    private void sendJsonResponse(HttpServletResponse resp, boolean success, String message) throws IOException {
        PrintWriter out = resp.getWriter();
        JSONObject response = new JSONObject();
        response.put("success", success);
        response.put("message", message);
        out.print(response.toJSONString());
        out.flush();
    }

    // 验证码验证方法（支持自定义 Session Key）
    private boolean validateCaptcha(HttpServletRequest request, String inputCaptcha, String sessionKey) {
        if (inputCaptcha == null || inputCaptcha.trim().isEmpty()) {
            return false;
        }

        // 从 Session 获取正确的验证码（使用指定的 Key）
        String correctCaptcha = (String) request.getSession().getAttribute(sessionKey);
        // 一次性使用
        request.getSession().removeAttribute(sessionKey);

        return correctCaptcha != null &&
                correctCaptcha.equalsIgnoreCase(inputCaptcha.trim());
    }
}